﻿using System;
using System.Web.UI;

/// <summary>
/// Summary description for InvisibleCaptcha
/// </summary>
public static class InvisibleCaptcha
{
    public static void InititializeCaptcha(Page page, StateBag viewState)
    {
        if (viewState["captchavalue"] == null)
        {
            viewState["captchavalue"] = Guid.NewGuid().ToString();
        }


        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.AppendLine("function SetCaptcha(){");
        sb.AppendLine("var form = document.getElementById('" + page.Form.ClientID + "');");
        sb.AppendLine("var el = document.createElement('input');");
        sb.AppendLine("el.type = 'hidden';");
        sb.AppendLine("el.name = 'captcha';");
        sb.AppendLine("el.value = '" + viewState["captchavalue"] + "';");
        sb.AppendLine("form.appendChild(el);}");

        page.ClientScript.RegisterClientScriptBlock(page.GetType(), "captchascript", sb.ToString(), true);
        page.ClientScript.RegisterOnSubmitStatement(page.GetType(), "captchayo", "SetCaptcha()");

    }

    /// <summary> 
    /// Gets whether or not the user is human 
    /// </summary> 
    public static bool IsCaptchaValid(System.Web.UI.Page page, StateBag viewState, bool raiseError)
    {
        bool result = false;

        if (viewState["captchavalue"] != null
            && page.Request.Form["captcha"] != null
            && page.Request.Form["captcha"].Length >= 36)
        {
            //substring first 36 characters to avoid duplicating Guid. Guid's string length is 36
            result = page.Request.Form["captcha"].Substring(0,36) == viewState["captchavalue"].ToString();
        }

        if (!result && raiseError)
        {
            page.Session[Constants.Session.ErrorMessage] = Constants.Error.ValidationFailed;
            page.Server.Transfer("~/Error.aspx");
        }

        return result;
    }


}
